package cn.milolab.djback.conf.jwt;

import java.util.Date;
import java.util.Map;
import javax.crypto.SecretKey;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;

/**
 * JWT Token工具类
 *
 * @description 通过createToken来创建token，然后通过parseToken来验签
 * @author 叶欣委
 *
 */

public class JwtUtil {
    // Token 过期时间
    private static final int EXPIRATION_TIME = 60 * 60 * 1000 * 10;
    // 签发方
    private static final String ISSUER = "yexinwei";
    // 密钥
    private static final String SECRET_KEY = "MEECAQAwEwYHKoZIzj0CAQYIKoZIzKPUsh92tWOqO0gmQv";

    /**
     * 通过自定义密钥SECRET_KEY来签名token
     *
     * @param claims
     * @return
     */
    public static String createToken(Map<String, Object> claims) {
        SecretKey key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(SECRET_KEY));
        String jws = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .setIssuer(ISSUER)
                .setIssuedAt(new Date()).signWith(key)
                .compact();
        return jws;
    }

    /**
     * 通过自定义密钥SECRET_KEY来解析验证token
     *
     * @param token
     * @return
     */
    public static Claims parseToken(String token) {
        SecretKey key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(SECRET_KEY));
        try {
            return Jwts.parserBuilder()
                    .setSigningKey(key)
                    .build()
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            return null;
        }
    }

}
